let axios = require('axios')
let cheerio = require('cheerio');
let fs = require('fs')
let task = {
  history: [], //交易记录
  info: {
    win: 0,
    out: 0,
    count: 0,
    omission: 0,
    maxOmission: 0,
    ratio: 0.96, //中奖赔率
    account: 1000, //原始账户金额
    power: 2, //没注金额
  },
  statistics(index = 0) {
    let tailList = [];

    function formatData() {
      let content = fs.readFileSync('./dist/data.json')
      JSON.parse(content).forEach((data) => {
        if (index === 0) {
          tailList.push(data.number.match(/\d$/)[0]); //个位
        } else if (index === 1) {
          tailList.push(data.number.match(/(\d)\d$/)[1]); //十位
        } else if (index === 2) {
          tailList.push(data.number.match(/(\d)\d\d$/)[1]); //百位
        } else if (index === 3) {
          tailList.push(data.number.match(/(\d)\d\d\d$/)[1]); //千位
        } else if (index === 4) {
          tailList.push(data.number.match(/(\d)\d\d\d\d$/)[1]); //万位
        }
      })
      fs.writeFileSync('./dist/tail.json', JSON.stringify(tailList))
    }
    formatData();
  },
  getSSC(cb) {
    let list = []
    let pageIndex = 1

    function get() {
      if (pageIndex > 81) {
        cb && cb(list)
        return false
      }
      console.log(`>>>>${pageIndex}`)
      let url = `https://fx.cp2y.com/cqssckj/?lid=10089&page=${pageIndex}&today=-1`
      console.log(`>>>${url}`)
      axios.get(url).then(res => {
        analyze(res.data)
      }).catch(err => {
        console.log(err)
      })
    }

    function analyze(html) {
      let $ = cheerio.load(html);
      $('table.kj-detail-table tr').each((i, tr) => {
        if (i > 0) {
          let trList = $(tr).find('td');
          let data = {
            name: $(trList[0]).text().match(/\d+/)[0].trim(),
            number: $(trList[1]).text().trim(),
          }
          list.push(data)
        }
      })
      pageIndex++;
      get()
    }
    get();
  },
  writeFile(data, fileName) {
    fs.writeFileSync(`./dist/${fileName}.json`, JSON.stringify(data))
  },
  /**
   * 更新数据
   */
  updateSSC() {
    this.getSSC(res => {
      this.writeFile(res.reverse(), 'new-data')
      this.merge();
    })
  },
  /**
   * 合并数据
   */
  merge() {
    let data = JSON.parse(fs.readFileSync('./dist/data.json'))
    let newData = JSON.parse(fs.readFileSync(`./dist/new-data.json`));
    newData = data.concat(newData);
    //排序
    newData.sort((a, b) => {
      return parseInt(a.name) - parseInt(b.name)
    })
    //去重
    let obj = {};
    newData = newData.reduce((cur, next) => {
      obj[next.name] ? "" : obj[next.name] = true && cur.push(next);
      return cur;
    }, []) //设置cur默认类型为数组，并且初始值为空的数组
    this.writeFile(newData, 'data')
  },
  analysis1() {
    let content = fs.readFileSync('./dist/tail.json')
    let list = JSON.parse(content)
    list.forEach(data => {
      console.log(data)
    })
  },
  /**
   * 统计遗漏，最大遗漏期，最多遗漏期，计算最佳遗漏期值
   */
  omission() {
    let content = fs.readFileSync('./dist/tail.json')
    let munList = JSON.parse(content)
    let max = {
      len: 0,
      num: -1,
      index: -1
    }
    let list = [];
    munList.forEach((n, index) => {
      n = parseInt(n)
      for (let i = 0; i < 10; i++) {
        if (i !== n) {
          list[i] = (list[i] || 0) + 1;
        } else {
          list[i] = 0;
        }
        if (list[i] > max.len) {
          max.len = list[i]
          max.num = i
          max.index = index
        }
      }
    })
    console.log(max)
  },
  getJSON() {
    let content = fs.readFileSync('./dist/tail.json')
    this.data = JSON.parse(content);
    return this.data
  },
  /**
   * 买指定次数没有出现的数字，一次买5个数字
   */
  algorithm1(max = 50, maxBuy = 5) {
    let data = this.getJSON();
    let list = [];
    for (let i = 0; i < 10; i++) {
      list[i] = {
        num: i,
        len: 0
      }
    }
    data.forEach((n, index) => {
      let flag = false;
      n = parseInt(n)
      for (let i = 0; i < 10; i++) {
        if (i !== n) {
          list[i].len++;
          if (list[i].len > max) {
            flag = true
          }
        } else {
          list[i].len = 0;
        }
      }
      if (flag) {
        //出现最大遗漏数字，筛选出来5个相对大的遗漏数字和下一期进行比较
        this.buy1(index, list, maxBuy);
      }
    })
    console.log(JSON.stringify(task.info));
    fs.writeFileSync('./dist/history.json', JSON.stringify(this.history))
  },
  /**
   * 猜大小
   */
  algorithm2(max = 50, maxBuy = 5) {
    let list = this.getJSON();
    let smallLen = 0;
    let largeLen = 0;
    list.forEach((number, index) => {
      if (list.length > index + 1) {
        if (number >= 5) {
          largeLen++
          smallLen = 0
          if (this.info.maxOmission < largeLen) {
            this.info.maxOmission = largeLen
            this.info.maxOmissionIndex = index
          }
        } else {
          largeLen = 0
          smallLen++
          if (this.info.maxOmission < smallLen) {
            this.info.maxOmission = smallLen
            this.info.maxOmissionIndex = index
          }
        }
        // 连着开大，买小
        if (largeLen > max) {
          // 判断下一期是否中奖
          //buy 小
          if (list[index + 1] < 5) {
            //赢
            this.info.win++
            this.info.count++;
            //更新账户信息
            this.info.account += parseInt(this.info.power * 5 * this.info.ratio)
            this.info.power = 2 //赔率
          } else {
            //未中
            this.info.out++
            this.info.count++;
            this.info.account -= parseInt(this.info.power * 5)
            let _power = this.info.power * 1
            if (_power < Math.pow(2, maxBuy)) {
              this.info.power = _power
            } else {
              this.info.power = Math.pow(2, maxBuy)
            }
          }
          this.history.push(JSON.parse(JSON.stringify(this.info)))
        }
        // 连着开小，买大
        if (smallLen > max) {
          // 判断下一期是否中奖
          //buy 大
          if (list[index + 1] >= 5) {
            //赢
            this.info.win++
            this.info.count++;
            //更新账户信息
            this.info.account += parseInt(this.info.power * 5 * this.info.ratio)
            this.info.power = 2 //赔率
          } else {
            //未中
            this.info.out++
            this.info.count++;
            this.info.account -= parseInt(this.info.power * 5)
            let _power = this.info.power * 1
            if (_power < Math.pow(2, maxBuy)) {
              this.info.power = _power
            } else {
              this.info.power = Math.pow(2, maxBuy)
            }
          }
          this.history.push(JSON.parse(JSON.stringify(this.info)))
        }
        //----------------------
        // if (this.info.power > Math.pow(2, maxBuy)) {
        //   this.info.power = 2
        // }

      }
    })
    console.log(JSON.stringify(this.info))
    fs.writeFileSync('./dist/history.json', JSON.stringify(this.history))
  },
  /**
   * 出现最大遗漏数字，筛选出来5个相对大的遗漏数字和下一期进行比较
   */
  buy1(index, list, maxBuy) {
    // ratio: 1.9, //中奖赔率
    // account: 10000, //原始账户金额
    // power: 2, //没注金额
    list = JSON.parse(JSON.stringify(list))
    list.sort((a, b) => {
      return b.len - a.len
    })
    let buyNumber = []
    for (let i = 0; i < 5; i++) {
      buyNumber.push(list[i].num)
    }
    if (this.data.length > (index + 1)) {
      this.info.count++
      if (buyNumber.indexOf(parseInt(this.data[index + 1])) > -1) {
        //赢
        this.info.win++
        if (this.info.omission > this.info.maxOmission) {
          this.info.maxOmission = this.info.omission
          this.info.maxOmissionIndex = index
          this.info.maxOmissionNo = buyNumber
        }
        this.info.omission = 0;
        //更新账户信息
        this.info.account += this.info.power * 5 * this.info.ratio
        this.info.power = 2
      } else {
        //赔
        this.info.out++
        this.info.omission += 1
        this.info.account -= this.info.power * 5
        this.info.power *= 2

      }
      if (this.info.power > Math.pow(2, maxBuy)) {
        this.info.power = 2
      }
      this.history.push(JSON.parse(JSON.stringify(this.info)))
    }
  },
  test1() {
    let arr = []
    // for (let i = 0; i < 20; i++) {
    //   for (let j = 0; j < 20; j++) {
    //     for (let y = 0; y < 20; y++) {
    //       arr.push({
    //         i,
    //         j,
    //         y
    //       })
    //     }
    //   }
    // }
    // fs.writeFileSync('./dist/test1.json',JSON.stringify(arr))

    let len = 9876543210;
    // len = 99
    for (let i = 0; i <= len; i++) {
      // if (isIsogram(i)) {
      arr.push(i)
      // }
    }
    console.log(arr.length)

    function isIsogram(str) {
      str += '';
      return !/^.*(.).*\1/i.test(str);
    }
    // 万*千*百=注
    // 注*遗漏期=遗漏值
    // 统计240期甚至更多期的中奖号码进行去重，生成最佳非中奖号码组合
    // 最佳非中奖号码组合:期数设为固定值，注数越大遗漏价值就越高，生成尽可能万千百位，位数最大的组合

    // 8*8*8*100
  },
  mock() {
    let arr = []
    for (let i = 0; i < 9999999; i++) {
      arr.push(Math.floor(Math.random() * 10))
    }
    fs.writeFileSync('./dist/tail.json', JSON.stringify(arr))
  }
}
// task.getJSON();

//更新数据
// task.updateSSC();
//合并数据  >>data.json
// task.merge();
// task.getSSC()
//统计数据  统计尾号到tail.json
// task.statistics(0);
// task.mock()
//统计遗漏
// task.omission();
//算法1  设定最大遗漏，进行买入
// task.algorithm1(60, 8); //遗漏期数，最大倍投数
// task.algorithm2(10, 800); //遗漏期数，最大倍投数
// console.log(JSON.stringify(task.info))
// task.test1()
// console.log('>>>END')

module.exports = task
